package com.kit.data.kitopeso.activity;

import android.content.Intent;
import android.net.Uri;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.kit.data.kitopeso.PathMaping;
import com.kit.data.kitopeso.R;
import com.kit.data.kitopeso.base.BaseActivity;
import com.kit.data.kitopeso.base.BaseDialog;
import com.kit.data.kitopeso.base.BaseParams;
import com.kit.data.kitopeso.databinding.KitoUserActivityBinding;
import com.kit.data.kitopeso.dialog.PhotoChooseDialog;
import com.kit.data.kitopeso.net.PU;
import com.kit.data.kitopeso.net.RxHttp;
import com.kit.data.kitopeso.net.U;
import com.kit.data.kitopeso.tools.AESCryptUtilJar;
import com.kit.data.kitopeso.tools.FileUtils;
import com.kit.data.kitopeso.tools.ImgUitls;
import com.kit.data.kitopeso.tools.JsonParse;
import com.kit.data.kitopeso.tools.LogUtil;
import com.kit.data.kitopeso.tools.ResUtils;
import com.kit.data.kitopeso.tools.ViewUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class KitoUserActivity extends BaseActivity<KitoUserActivityBinding> {


    String url = "";

    String name = "";


    PhotoChooseDialog mPhotoChooseDialog;

    ActivityResultLauncher<PickVisualMediaRequest> pickMedia;


    @Override
    protected KitoUserActivityBinding initViewBinding(LayoutInflater inflater) {
        return KitoUserActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        binding.tvInput.setType(PU.P210);
        binding.tvInput.clearFocus();


        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });

        binding.tvBtn.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P169, "");
            submit();
        });

        binding.tvIconLayout.setOnClickListener(view -> {
            ViewUtils.viewScale(view);
            PU.userBuriedPoint(PU.P167, "");
            showPhotoChooseDialog();
        });

    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P164;
        UP_TYPE2 = PU.P165;
        pickMedia = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                String imgPath = FileUtils.getFileAbsolutePath(getActivity(), uri);
                imageUpload(uri, imgPath);
                LogUtil.e("me", "imgPath->" + imgPath);
            }
        });
        loadData();
        getUserInfo();
    }

    void loadData() {

        if (getActivity() != null && !isFinishing()) {
            if (!TextUtils.isEmpty(url)) {
                Glide.with(binding.tvIcon.getContext()).load(url).placeholder(R.color.placeholder_icon).into(binding.tvIcon);
            }

            if (!TextUtils.isEmpty(name)) {
                binding.tvInput.setText(name);
            }
        }
    }


    void getUserInfo() {
        showLoading("");

        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[75]);
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_MAIN_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        RxHttp.post(U.commonUrl, AESCryptUtilJar.encryptDefault(json.toString()), heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "getUserInfo json->" + json1);
                            if (JsonParse.getCode(json1)) {
                                JSONObject object = JsonParse.getAbUserInfoJson2Obj(json1);
                                if (object != null) {
                                    try {
                                        name = object.getString("name");
                                        url = object.getString("url");
                                    } catch (JSONException ignored) {
                                    }
                                }
                                loadData();
                            } else {
                                showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.login_faile));
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });

    }

    void submit() {

        showLoading("");

        name = binding.tvInput.getText().toString();

        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[74]);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("name", name);
        jsonObject.addProperty("url", url);
        json.addProperty("userInfo", jsonObject.toString());


        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_MAIN_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        RxHttp.post(U.commonUrl, AESCryptUtilJar.encryptDefault(json.toString()), heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "submit json->" + json1);
                            if (JsonParse.getCode(json1)) {
                                showToastDialog(R.mipmap.hit_icon1, getResources().getString(R.string.myuser_save_hit));
                            } else {
                                showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.login_faile));
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });

    }

    void showPhotoChooseDialog() {
        if (mPhotoChooseDialog == null) {
            mPhotoChooseDialog = new PhotoChooseDialog(this);
        }
        mPhotoChooseDialog.setOnBtnClickListener(new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                int type = mPhotoChooseDialog.getType();
                if (type == 1) {
                    toTakePhoto();
                } else if (type == 2) {
                    formAlbum();
                }
            }

            @Override
            public void btnOnClickCancel() {

            }

            @Override
            public void btnOnClickColse() {

            }
        });
        mPhotoChooseDialog.show();
    }

    void toTakePhoto() {
        Intent intent = new Intent(this, KitoCameraActivity.class);
        intent.putExtra("isHide", true);
        someActivityResultLauncher.launch(intent);
    }


    void formAlbum() {
        if (pickMedia != null) {
            pickMedia.launch(new PickVisualMediaRequest.Builder()
                    .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                    .build());
        }
    }

    void imageUpload(Uri imageUri, String path) {
        showLoading(ResUtils.s(R.string.upload));
        LogUtil.e("me", "URL.uploadUrl->" + U.uploadUrl);
        RxHttp.uploadImage(U.uploadUrl, ImgUitls.compressToTargetSize(this, imageUri, 1024, path))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        if (!TextUtils.isEmpty(s)) {
                            if (JsonParse.getCode(s)) {
                                url = JsonParse.imageUploadJson2Obj(s);
                                LogUtil.e("me", "imageUpload url->" + url);
                                if (!TextUtils.isEmpty(url)) {
                                    showToastDialog(R.mipmap.hit_icon1, ResUtils.s(R.string.upload_completed));
                                    loadData();
                                }
                            } else {
                                showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), s));
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (e != null) {
                            LogUtil.e("me", "imageUpload e->" + e);
                        }
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, ResUtils.s(R.string.upload_failed));
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });
    }


    final ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                LogUtil.e("me", "--onActivityResult--");
                if (result.getResultCode() == RESULT_OK) {
                    Intent data = result.getData();
                    if (data != null) {
                        url = data.getStringExtra("url");
                        LogUtil.e("me", "onActivityResult url->" + url);
                        if (!TextUtils.isEmpty(url)) {
                            loadData();
                        }
                    }
                }
            }
    );


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPhotoChooseDialog != null) {
            mPhotoChooseDialog.dismiss();
        }
    }


}
